/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador;

import comu.Configuracio;
import controlador.autogenerats.CollitaJpaController;
import entity.Camp;
import entity.Collita;
import entity.Produccio;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author David
 */
public class CollitaControlador extends CollitaJpaController{

    public static String getTrazabilitatCodeFalse(Produccio produccio, Date data) {
        //Format del Codi:  ####ddmmyy
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy");
        String out = "";
        out += String.valueOf(produccio.getId()+10000).substring(1);
        out += sdf.format(data);
        return out;
    }
    
    public CollitaControlador() {
        super(Persistence.createEntityManagerFactory(Configuracio.PERSISTANCE_UNIT));
    }
    
    public static String getTrazabilitatCode(Collita collita){
        //Format del Codi:  ####ddmmyy
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy");
        String out = "";
        out += String.valueOf(collita.getProduccioId().getId()+10000).substring(1);
        out += sdf.format(collita.getData());
        return out;
    }

    public List<Collita> findCollitaEntitiesByProduccio(Produccio produccio) {
        EntityManager em = getEntityManager();
        try{
            Query q = em.createNativeQuery("select * from collita where `produccio_id` LIKE "+ produccio.getId(), Collita.class);
            Iterator it = q.getResultList().iterator();
            ArrayList<Collita> llista = new ArrayList<Collita>();
            while(it.hasNext()){
                llista.add((Collita) it.next());
            }
            return llista;
        } finally {
            em.close();
        }
    }

}